var NwBuilder = require('nw-builder');
var mergejs = require('merge-express-js');

var mslibrary = require('ms-common-library');

var exec = require('child_process').exec;

var path = require('path');

var fs = require('fs');
var savefile = mslibrary.savefile;
var nwversion = '0.43.3'
class BuildWebOS {
	jstoc(Callback) {
		var jsfile = path.join(__dirname, "main.js");
		var dinfile = path.join(__dirname, "app/www.bin");

		var cmdStr = '/Users/musa/.nwjs/' + nwversion + '-sdk/nwjc ' + jsfile + ' ' + dinfile;
		exec(cmdStr, function (error, stdout, stderr) {

			if (error) {
				Callback(error)
			} else {
				var log = path.join(__dirname, "v8.log");
				var wwwjs = path.join(__dirname, "./config/js/www.js");
				fs.unlinkSync(log)
				fs.unlinkSync(wwwjs)
				fs.unlinkSync(jsfile)
				Callback()
			}
		});
	}
	Build(Callback) {
		var basePath = path.join(__dirname, './app');
		var UserFile = __dirname
		var UserFile = process.env.USERPROFILE ? process.env.USERPROFILE + "//.nwbuild_cache" : process.env.HOME + "/.nwbuild_cache";
		var option = {
			appVersion: "1.0.0.0",
			version: "1.0.0.0",
			buildDir: __dirname + '/cache_file/build',
			cacheDir: UserFile + '/cache_file',
			appName: "Node Apps",
			flavor: 'normal',
			zip: false,
			files: basePath + '/**/**/**/**', // 包含文件
			platforms: ["osx64"], // 打包的平台["osx64", "win32"],
			version: nwversion,
			"nwjsBuilder": {
				"productName": "NWJS-WEB-OS",
				"productVersion": "1.0.0.0",
				"fileDescription": "NWJS-WEB-OS"
			},
			macIcns: path.join(__dirname, "./config/app.icns")
		};
		//option.winIco=path.join(__dirname, "./config/app.ico");

		var nw = new NwBuilder(option);
		nw.on('log', console.log);
		nw.build().then(function () {
			Callback(null)
		}).catch(function (err) {
			Callback(err);
		});
	}
	constructor() {
		var self = this;
		var wwwjs = path.join(__dirname, "./config/js/www.js");
		fs.exists(wwwjs, function (off) {
			if (off) {
				mergejs.MergeNode({
						ProjectAddress: path.join(__dirname, "./config/js"),
						module: false,
						minjs: true,
						RelativeAddress: "./drive.js"
					}, [],
					function (code, error, Paramet) {
						savefile(path.join(__dirname, "main.js"), code, function () {
							self.jstoc(function (error) {
								self.Build(function () {
									console.log("---------ok----------")
								})
							})
						})
					});
			} else {
				self.Build(function () {
					console.log("---------ok----------")
				})
			}
		})
	}
}
new BuildWebOS()